﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using _表达式树探究.Models;

namespace _表达式树探究
{
    class Program
    {
        static void Main(string[] args)
        {
            PersonInfo[] personList =
            {
                new PersonInfo(){Id = 1,Name = "张三",Birthday = DateTime.Now.AddYears(-22),Sex = "男",Hobby = "象棋"},
                new PersonInfo(){Id = 2,Name = "小兰",Birthday = DateTime.Now.AddYears(-18),Sex = "女",Hobby = "篮球"},
                new PersonInfo(){Id = 3,Name = "王五",Birthday = DateTime.Now.AddYears(-25),Sex = "男",Hobby = "五子棋,象棋"},
                new PersonInfo(){Id = 4,Name = "小红",Birthday = DateTime.Now.AddYears(-27),Sex = "女",Hobby = "围棋,羽毛球"},
                new PersonInfo(){Id = 5,Name = "马六",Birthday = DateTime.Now.AddYears(-31),Sex = "男",Hobby = "足球,篮球"}
            };

            var data1 = personList.OrderByDescending(x => new { x.Sex, x.Birthday });


            bool asc = true;

            string orderFiled = "Birthday";

            string orderWay = asc ? "orderBy" : "OrderByDescending";

            Type entityType = typeof(PersonInfo);

            var paraInfo = entityType.GetProperty(orderFiled);


            //创建表达式变量参数
            var parameters = Expression.Parameter(entityType, "x");

            //创建属性访问器表达式
            var memberExpressions = Expression.MakeMemberAccess(parameters, paraInfo);

            //构建 x=>x.Birthday
            var body = Expression.Lambda(memberExpressions, parameters);

            //调用
            var resultExpression = Expression.Call(typeof(Queryable), orderWay, new Type[] { entityType, paraInfo.PropertyType }, personList.AsQueryable().Expression,
                Expression.Quote(body));

            //返回数据
            var dataRel = personList.AsQueryable().Provider.CreateQuery<PersonInfo>(resultExpression).ToList();





        }
    }
}
